package com.example.sangong.interceptor;

import cn.hutool.core.util.StrUtil;
import com.example.sangong.utils.RedissonUtils;
import com.example.sangong.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    private static ThreadLocal<LocalDateTime> starTime = new ThreadLocal<>();
    @Autowired
    private RedissonUtils redissonUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //添加这行代码，让OPTIONS请求通过
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        String outerToken = request.getHeader("OuterToken");
        if (StrUtil.isNotBlank(outerToken)) {

            if (redissonUtils.isExists(outerToken)) {
                return true;
            } else {
                throw new RuntimeException(outerToken + "redis token 不存在");
            }
        }
        String token = request.getHeader("Token");
        if (StrUtil.isBlank(token)) {
            throw new RuntimeException("没有传递token参数");
        }
        if (TokenUtil.verify(token)) {
            return HandlerInterceptor.super.preHandle(request, response, handler);
        } else {
            throw new RuntimeException("token失效");
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
            modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception
            ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
